package mysql

import (
	"bawei_2112a_shop/appconfig"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"sync"
)

var (
	MysqlClient *gorm.DB
	err         error
	once        sync.Once
)

func InitMySQL() {
	once.Do(func() {

		host := appconfig.AppConf.MySQLConfig.Host
		port := appconfig.AppConf.MySQLConfig.Port
		user := appconfig.AppConf.MySQLConfig.User
		password := appconfig.AppConf.MySQLConfig.Password
		dbname := appconfig.AppConf.MySQLConfig.DbName
		dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, host, port, dbname)
		//dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
		MysqlClient, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
		if err != nil {
			fmt.Println("MySQL 连接失败：", err)
			return
		}

		fmt.Println("MySQL 连接成功")
		MysqlClient.AutoMigrate(new(Goods), new(Order), new(OrderItem))

	})
}
